package org.asiainfo.common.tenant.manager;

import cn.hutool.core.util.ObjectUtil;
import org.asiainfo.common.core.constant.GlobalConstants;
import org.asiainfo.common.core.utils.StringUtils;
import org.asiainfo.common.redis.manager.FlexSpringCacheManager;
import org.asiainfo.common.tenant.utils.TenantHelper;
import org.springframework.cache.Cache;

/**
 * 重写 cacheName 处理方法 支持多租户
 *
 * @author dotor-ww
 */
public class TenantSpringCacheManager extends FlexSpringCacheManager {

    public TenantSpringCacheManager() {
    }

    /**
     * 获取缓存
     *
     * @param name 缓存名称
     * @return 缓存信息
     */
    @Override
    public Cache getCache(String name) {
        if (StringUtils.contains(name, GlobalConstants.GLOBAL_REDIS_KEY)) {
            return super.getCache(name);
        }
        Long tenantId = TenantHelper.getTenantId();
        if (ObjectUtil.isNull(tenantId)) {
            return super.getCache(name);
        }
        if (StringUtils.startsWith(name, String.valueOf(tenantId))) {
            // 如果存在则直接返回
            return super.getCache(name);
        }
        return super.getCache(tenantId + ":" + name);
    }
}
